import os
import asyncio
from typing import List, Dict, Any, Optional
from openai import AsyncOpenAI
from dotenv import load_dotenv

load_dotenv()

class KimiClient:
    """
    Kimi API客户端，用于与Moonshot AI的Kimi大模型交互
    """
    
    def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
        self.api_key = api_key or os.getenv("KIMI_API_KEY")
        self.base_url = base_url or os.getenv("KIMI_BASE_URL", "https://api.moonshot.cn/v1")
        
        if not self.api_key:
            raise ValueError("KIMI_API_KEY is required. Please set it in .env file or pass as parameter.")
        
        self.client = AsyncOpenAI(
            api_key=self.api_key,
            base_url=self.base_url
        )
    
    async def chat_completions(
        self,
        messages: List[Dict[str, str]],
        model: str = "moonshot-v1-8k",
        temperature: float = 0.7,
        max_tokens: Optional[int] = None
    ) -> str:
        """
        发送聊天消息到Kimi API
        
        Args:
            messages: 消息列表，格式为 [{"role": "user", "content": "..."}]
            model: 模型名称
            temperature: 温度参数，控制随机性
            max_tokens: 最大token数
            
        Returns:
            AI响应内容
        """
        try:
            response = await self.client.chat.completions.create(
                model=model,
                messages=messages,
                temperature=temperature,
                max_tokens=max_tokens
            )
            return response.choices[0].message.content
        except Exception as e:
            raise Exception(f"Kimi API调用失败: {str(e)}")
    
    async def generate_summary(self, text: str, max_length: int = 500) -> str:
        """
        生成文本摘要
        
        Args:
            text: 需要摘要的文本
            max_length: 摘要最大长度
            
        Returns:
            摘要文本
        """
        prompt = f"请为以下文本生成一个简洁的摘要，限制在{max_length}字以内：\n\n{text}"
        
        messages = [{"role": "user", "content": prompt}]
        return await self.chat_completions(messages, temperature=0.3, max_tokens=max_length)
    
    async def generate_report_section(self, topic: str, context: str, section_type: str) -> str:
        """
        生成研究报告的特定章节
        
        Args:
            topic: 研究主题
            context: 上下文信息
            section_type: 章节类型 (如 "introduction", "background", "analysis"等)
            
        Returns:
            生成的章节内容
        """
        prompts = {
            "introduction": f"请为{topic}主题的研究报告写一个引人入胜的引言，介绍该主题的重要性和研究意义。",
            "background": f"请提供{topic}主题的详细背景信息，包括历史发展、现状和相关概念。",
            "analysis": f"基于以下信息，对{topic}进行深入分析：\n{context}",
            "conclusion": f"基于以上分析，为{topic}主题提供总结和前瞻性建议。"
        }
        
        prompt = prompts.get(section_type, f"请基于以下信息，为{topic}主题生成相关内容：\n{context}")
        
        messages = [{"role": "user", "content": prompt}]
        return await self.chat_completions(messages, temperature=0.5)